package guice.boot.archive.container.registry;

import com.sun.istack.internal.NotNull;
import guice.boot.archive.common.util.StringUtils;
import guice.boot.archive.spi.registry.ServiceMetaData;
import guice.boot.archive.spi.registry.ServiceProvider;


public class ServiceMetaDataImpl implements ServiceMetaData {

    private String uniqueId;
    private Class<?> interfaceClass;
    private ServiceProvider serviceProvider;

    public ServiceMetaDataImpl(@NotNull String uniqueId, @NotNull Class<?> interfaceClass, @NotNull ServiceProvider serviceProvider) {

        this.uniqueId = uniqueId;
        this.interfaceClass = interfaceClass;
        this.serviceProvider = serviceProvider;
    }

    @Override
    public String getUniqueId() {
        return uniqueId;
    }

    @Override
    public Class<?> getServiceInterfaceClass() {
        return interfaceClass;
    }

    @Override
    public ServiceProvider getServiceProvider() {
        return serviceProvider;
    }

    @Override
    public String getServiceName() {
        if (StringUtils.isEmpty(uniqueId)) {
            return interfaceClass.getCanonicalName();
        } else {
            return String.format("%s:%s", interfaceClass.getCanonicalName(), uniqueId);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        ServiceMetaData serviceMetadata = (ServiceMetaData) obj;

        if (!uniqueId.equals(serviceMetadata.getUniqueId())) {
            return false;
        }

        if (!interfaceClass.equals(serviceMetadata.getServiceInterfaceClass())) {
            return false;
        }

        return serviceProvider.equals(serviceMetadata.getServiceProvider());
    }

    @Override
    public int hashCode() {
        int result = 1;
        result = 31 * result + uniqueId.hashCode();
        result = 31 * result + interfaceClass.hashCode();
        result = 31 * result + serviceProvider.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return String.format("ServiceMetaData{service=\'%s\', provider=\'%s\'}", getServiceName(),
                getServiceProvider().toString());
    }
}